﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SAPBoAddon;
using SAPbouiCOM;

namespace BoAddonBiz_FreightForwarder.Sea
{
    [BoAddonBiz_FreightForwarder.BusinessBase.ControlB1Form(IsNew = true, FormType = B1FormTypes.ado_AVA_SE_Packing)]
    public class B1Form_Packing : B1Form_BaseOperationSon
    {
        #region override
        public override string ThisSubTableName { get { return "@AVA_SE_PCK1"; } }
        public override string ThisSubTableName2 { get { return "@AVA_SE_PCK2"; } }
        public override string FatherField { get { return "U_IsBox"; } }
        public override string FatherUDS { get { return "OPCK_UID"; } }
        public override string ThisTableName { get { return "@AVA_SE_OPCK"; } }
        public override string ThisObjectCode { get { return "AVA_SE_Packing"; } }
        protected override void FormInfoSetting(SAPBoAddon.B1FormSetting FormSetting)
        {
            FormSetting.FormType = B1FormTypes.ado_AVA_SE_Packing;
            FormSetting.FormFileName = "AVA_SE_PackingForm.srf";
            base.FormInfoSetting(FormSetting);
            FormSetting.MatrixSetting.MtxUID = "mtx_0";
            FormSetting.MatrixSetting.NotAllowNoLineSave = false;
            FormSetting.MatrixSetting.AutoAddNewLine = true;
            FormSetting.MatrixSetting.MenuAddNewLine = true;//如果不设置为false，在事件前也会执行系统添加行删除行操作
            FormSetting.MatrixSetting.AutoLineKeyCol = "col_5";//箱量
            FormSetting.MatrixSetting.BeforeSaveDeleteNoValueLine = true;
            FormSetting.MatrixSetting.BeforeSaveFixDbDataSourceData = true;
            FormSetting.MatrixSetting.TableKeyField = "LineId";
            FormSetting.MatrixSetting.TableVisOrder = "VisOrder";
            FormSetting.MatrixSetting.PrimaryLineCol = "col_f";
            FormSetting.MatrixSetting.TableName = "@AVA_SE_PCK1";
            FormSetting.MatrixSetting.Add();
        }

        protected override void InitializeForm(B1FormInitializePar InitPar)
        {
            this.CurrentForm.Freeze(true);
            base.InitializeForm(InitPar);

            Utils.InitialMatrixComboBox(this.SBOCompany, this.CurrentForm.Items.Item("mtx_0").Specific, "col_4", "Code", "Name", "@AVA_FF_OBOX", "Code", null, null, true, true);
            Utils.InitialMatrixComboBox(this.SBOCompany, this.CurrentForm.Items.Item("mtx_0").Specific, "col_8", "Code", "Name", "@AVA_FF_OPRI", "Code", null, "U_Type = N'Number' OR U_Type = N'Pack'", true, false);// 包装形式 取值 计量单位里的  modified by WangPeng 2012年8月29日 18:56:43

            (this.CurrentForm.Items.Item("mtx_0").Specific as Matrix).AutoResizeColumns();
            if (this.CurrentForm.Mode == BoFormMode.fm_ADD_MODE)
            {
                //根据FCL计算箱量
                DBDataSource dbds1 = this.CurrentForm.DataSources.DBDataSources.Item("@AVA_SE_PCK1");
                dbds1.Clear();
                if (BNOForm.DataSources.DBDataSources.Item("@AVA_SE_OBNO").GetValue("U_ContainerType", 0).Trim() == "1")
                {
                    for (int i = 0; i < BNOForm.DataSources.DBDataSources.Item("@AVA_SE_BNO6").Size; i++)
                    {
                        double quantity = 0;
                        double.TryParse(BNOForm.DataSources.DBDataSources.Item("@AVA_SE_BNO6").GetValue("U_Quantity", i), out quantity);
                        string boxType = BNOForm.DataSources.DBDataSources.Item("@AVA_SE_BNO6").GetValue("U_BoxType", i).Trim();
                        for (int ii = 0; ii < Convert.ToInt32(quantity); ii++)
                        {
                            SAPBoAddon.B1Assistant.DBDataSource.AddNewRecordTo(dbds1, 1, "LineId", "VisOrder");
                            dbds1.SetValue("U_BoxType", dbds1.Offset, boxType);
                        }
                    }
                    (this.CurrentForm.Items.Item("mtx_0").Specific as Matrix).LoadFromDataSource();
                }
                else
                {
                    SAPBoAddon.B1Assistant.Matrix.AutoAddNewLine(CurrentForm, "mtx_0", "col_f", "@AVA_SE_PCK1", -1, "Lineid", "VisOrder", true);
                }
            }
            this.CurrentForm.Freeze(false);
        }
        #endregion
        #region constractor
        public B1Form_Packing()
            : base()
        {
            this.frm_ItemEvent += new IB1FormEvents.B1ItemEventEventHandler(B1Form_Packing_frm_ItemEvent);
            this.frm_ChooseFormListEvent += new IB1FormEvents.B1ChooseFormListEventEventHandler(B1Form_Packing_frm_ChooseFormListEvent);
        }
        #endregion
        #region events
        void B1Form_Packing_frm_ChooseFormListEvent(SAPBoAddon.B1AddonBase.B1ChooseFormList pVal, ref bool BubbleEvent)
        {
            //5订舱代理，8通知人，11发货人，12收货人
            SAPbouiCOM.DBDataSource dbds = this.CurrentForm.DataSources.DBDataSources.Item("@AVA_SE_PCK2");
            SAPbouiCOM.Conditions cons;
            SAPbouiCOM.Condition con;
            SAPbouiCOM.ChooseFromList cfl;
            SAPbobsCOM.Recordset oRst = (SAPbobsCOM.Recordset)SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            if (pVal.Before_Action)
            {
                cfl = this.CurrentForm.ChooseFromLists.Item(pVal.ChooseFromListUID);
                switch (pVal.ChooseFromListUID)
                {
                    case "CFL_Delegate":
                        cons = new SAPbouiCOM.Conditions();
                        con = cons.Add();
                        con.Alias = "QryGroup5";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = BoConditionRelationship.cr_AND;
                        con = cons.Add();
                        con.Alias = "validFor";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        cfl.SetConditions(cons);
                        break;
                    case "CFL_Notifier":
                        cons = new SAPbouiCOM.Conditions();
                        con = cons.Add();
                        con.Alias = "QryGroup8";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = BoConditionRelationship.cr_AND;
                        con = cons.Add();
                        con.Alias = "validFor";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        cfl.SetConditions(cons);
                        break;
                    case "CFL_Receiver":
                        cons = new SAPbouiCOM.Conditions();
                        con = cons.Add();
                        con.Alias = "QryGroup12";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = BoConditionRelationship.cr_AND;
                        con = cons.Add();
                        con.Alias = "validFor";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        cfl.SetConditions(cons);
                        break;
                    case "CFL_Sender":
                        cons = new SAPbouiCOM.Conditions();
                        con = cons.Add();
                        con.Alias = "QryGroup11";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = BoConditionRelationship.cr_AND;
                        con = cons.Add();
                        con.Alias = "validFor";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        cfl.SetConditions(cons);
                        break;
                }
            }
            else
            {
                Matrix mtx = (SAPbouiCOM.Matrix)this.CurrentForm.Items.Item(pVal.ItemUID).Specific;
                dbds.Offset = SAPBoAddon.B1Assistant.Matrix.GetdbDsOffset(mtx, pVal.Row, "col_f", dbds);
                mtx.GetLineData(pVal.Row);
                switch (pVal.ChooseFromListUID)
                {
                    case "CFL_Delegate":
                        dbds.SetValue("U_DelegateCode", dbds.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        dbds.SetValue("U_Delegate", dbds.Offset, string.IsNullOrEmpty(pVal.SelectedObjects.GetValue("CardName", 0).ToString()) ? pVal.SelectedObjects.GetValue("CardFName", 0).ToString() : pVal.SelectedObjects.GetValue("CardName", 0).ToString());
                        break;
                    case "CFL_Notifier":
                        dbds.SetValue("U_NotifierCode", dbds.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        dbds.SetValue("U_Notifier", dbds.Offset, string.IsNullOrEmpty(pVal.SelectedObjects.GetValue("CardFName", 0).ToString()) ? pVal.SelectedObjects.GetValue("CardName", 0).ToString() : pVal.SelectedObjects.GetValue("CardFName", 0).ToString().Trim());
                        break;
                    case "CFL_Receiver":
                        dbds.SetValue("U_ReceiverCode", dbds.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        dbds.SetValue("U_Receiver", dbds.Offset, string.IsNullOrEmpty(pVal.SelectedObjects.GetValue("CardFName", 0).ToString()) ? pVal.SelectedObjects.GetValue("CardName", 0).ToString() : pVal.SelectedObjects.GetValue("CardFName", 0).ToString().Trim());
                        break;
                    case "CFL_Sender":
                        dbds.SetValue("U_SenderCode", dbds.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        dbds.SetValue("U_Sender", dbds.Offset, string.IsNullOrEmpty(pVal.SelectedObjects.GetValue("CardFName", 0).ToString()) ? pVal.SelectedObjects.GetValue("CardName", 0).ToString() : pVal.SelectedObjects.GetValue("CardFName", 0).ToString().Trim());
                        break;
                    case "CFL_EndPort":
                        dbds.SetValue("U_EndPortCode", dbds.Offset, pVal.SelectedObjects.GetValue("DocEntry", 0).ToString());
                        dbds.SetValue("U_EndPortThCode", dbds.Offset, pVal.SelectedObjects.GetValue("U_PortCode", 0).ToString());
                        dbds.SetValue("U_EndPort", dbds.Offset, pVal.SelectedObjects.GetValue("U_PortNameE", 0).ToString().Trim());
                        break;
                }
                mtx.SetLineData(pVal.Row);
            }
        }

        void B1Form_Packing_frm_ItemEvent(SAPBoAddon.B1AddonBase.B1ItemEvent pVal, ref bool BubbleEvent)
        {
            if (pVal.BeforeAction)
            {
                if (pVal.ItemUID == "1" && pVal.EventType == BoEventTypes.et_CLICK)
                {
                    if (this.CurrentForm.Mode == BoFormMode.fm_ADD_MODE || this.CurrentForm.Mode == BoFormMode.fm_UPDATE_MODE)
                    {
                        (this.CurrentForm.Items.Item("mtx_0").Specific as Matrix).FlushToDataSource();
                        Utils.SetBoxAndCargoQuantityDescription(SBOApp, BNOForm.UniqueID, new Arabic2Engish().NumberToString);
                        Utils.SetBoxAndSealNumber(SBOApp, BNOForm.UniqueID);
                        //更新服务页签
                        UpdateBOService();
                        //if (BNOForm.Mode == BoFormMode.fm_UPDATE_MODE) BNOForm.Items.Item("1").Click(BoCellClickType.ct_Linked);
                    }
                }
            }
            else
            {
                #region 验证箱号窗体
                if (pVal.ItemUID == "mtx_0" && pVal.ColUID == "col_5" && pVal.EventType == BoEventTypes.et_VALIDATE)
                {
                    if (this.CurrentForm.Mode == BoFormMode.fm_ADD_MODE || this.CurrentForm.Mode == BoFormMode.fm_UPDATE_MODE)
                    {
                        if ((this.CurrentForm.Items.Item(pVal.ItemUID).Specific as Matrix).GetCellSpecific(pVal.ColUID, pVal.Row).Value.ToString().Length == 0)
                        {
                            SAPbouiCOM.Form containerForm = SAPBoAddon.B1Assistant.Form.LoadToSBOApplciation(System.Windows.Forms.Application.StartupPath + @"\Form\AVA_SE_ContainerForm.srf", "", true);
                            containerForm.DataSources.UserDataSources.Item("ParentUID").Value = this.CurrentForm.UniqueID;
                            containerForm.DataSources.UserDataSources.Item("Matrix").Value = pVal.ItemUID;
                            containerForm.DataSources.UserDataSources.Item("Col").Value = pVal.ColUID;
                            containerForm.DataSources.UserDataSources.Item("Row").Value = pVal.Row.ToString();
                        }
                    }
                }
                #endregion
                //产装
                if (pVal.ItemUID == "54" && pVal.EventType == BoEventTypes.et_CLICK)
                {
                    SAPBoAddon.B1Assistant.Item.SetVisible(CurrentForm, new string[] { "17", "1000002", "23", "19", "24", "20", "25", "21", "26", "22", "27" }, true);
                    SAPBoAddon.B1Assistant.Item.SetVisible(CurrentForm, new string[] { "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50" }, false);
                }
                //内装
                if (pVal.ItemUID == "1000003" && pVal.EventType == BoEventTypes.et_CLICK)
                {

                    SAPBoAddon.B1Assistant.Item.SetVisible(CurrentForm, new string[] { "17", "1000002", "23", "19", "24", "20", "25", "21", "26", "22", "27" }, false);
                    SAPBoAddon.B1Assistant.Item.SetVisible(CurrentForm, new string[] { "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50" }, true);
                }
                //箱号和封号发生变化时，重新计算件数和体积
                if (pVal.ItemUID == "mtx_0" && (pVal.ColUID == "col_5" || pVal.ColUID == "col_6") && pVal.ItemChanged)
                {
                    decimal Quantity = 0;
                    decimal Volume = 0;
                    decimal GrossWeight = 0;

                    SAPbouiCOM.DBDataSource BNO1 = BNOForm.DataSources.DBDataSources.Item("@AVA_SE_BNO1");
                    if (decimal.TryParse(BNO1.GetValue("U_Quantity", 0).Trim(), out Quantity) == false)
                    {
                        return;
                    }
                    if (decimal.TryParse(BNO1.GetValue("U_Volume", 0).Trim(), out Volume) == false)
                    {
                        return;
                    }
                    if (decimal.TryParse(BNO1.GetValue("U_GrossWeight", 0).Trim(), out GrossWeight) == false)
                    {
                        return;
                    }

                    SAPbouiCOM.Matrix mtx = this.CurrentForm.Items.Item("mtx_0").Specific;
                    SAPbouiCOM.DBDataSource dbds = this.CurrentForm.DataSources.DBDataSources.Item("@AVA_SE_PCK1");
                    int BoxQty = 0;
                    for (int i = 1; i <= mtx.RowCount; i++)
                    {
                        var box = SAPBoAddon.B1Assistant.Matrix.GetCellValue(mtx, "col_4", i).ToString();
                        box = box.Substring(0, 2);
                        BoxQty += (Convert.ToInt32(box) / 20);
                    }
                    int result = 0;
                    for (int i = 1; i <= mtx.RowCount; i++)
                    {
                        mtx.GetLineData(i);
                        var box = SAPBoAddon.B1Assistant.Matrix.GetCellValue(mtx, "col_4", i).ToString();
                        box = box.Substring(0, 2);
                        decimal boxbase = (Convert.ToInt32(box) / 20);
                        int Qty = Math.DivRem(Convert.ToInt32(Quantity), Convert.ToInt32(BoxQty), out result);
                        if (i == mtx.RowCount)
                            Qty += result;

                        dbds.SetValue("U_Quantity", i - 1, (Qty * boxbase).ToString());
                        dbds.SetValue("U_Volume", i - 1, (Volume / BoxQty * boxbase).ToString());
                        dbds.SetValue("U_Weight", i - 1, (GrossWeight / BoxQty * boxbase).ToString());
                        mtx.SetLineData(i);
                    }
                    mtx.LoadFromDataSourceEx();
                }
            }
        }

        #endregion
        #region methods
        /// <summary>
        /// 更新业务单的服务页签
        /// </summary>
        private void UpdateBOService()
        {
            if (SAPBoAddon.B1Assistant.Item.GetValue(BNOForm, "FCL").ToString() == "N")
                return;
            IList<Packing> Packings = new List<Packing>();
            SAPbouiCOM.Matrix oMtx = CurrentForm.Items.Item("mtx_0").Specific;
            for (int i = 1; i <= oMtx.VisualRowCount; i++)
            {
                Packing Packing = new Packing();
                Packing.BoxType = oMtx.GetCellSpecific("col_4", i).Value.ToString();
                Packing.BoxCode = oMtx.GetCellSpecific("col_5", i).Value.ToString();
                Packing.SealCode = oMtx.GetCellSpecific("col_6", i).Value.ToString();
                Packings.Add(Packing);
            }
            if (Packings.Count <= 0)
                return;
            SAPbouiCOM.Matrix oPMtx = BNOForm.Items.Item("mtxService").Specific;
            SAPbouiCOM.DBDataSource dbds = BNOForm.DataSources.DBDataSources.Item("@AVA_SE_BNO6");
            oPMtx.Clear();
            dbds.Clear();
            foreach (Packing item in Packings)
            {
                dbds.InsertRecord(dbds.Size);
                dbds.Offset = dbds.Size - 1;
                oPMtx.AddRow();
                oPMtx.GetLineData(dbds.Size);
                dbds.SetValue("U_BoxType", dbds.Offset, item.BoxType);
                dbds.SetValue("U_BoxNumber", dbds.Offset, item.BoxCode);
                dbds.SetValue("U_SealNumber", dbds.Offset, item.SealCode);
                oPMtx.SetLineData(dbds.Size);
            }
            oPMtx.LoadFromDataSourceEx();
            BNOForm.DataSources.DBDataSources.Item("@AVA_SE_BNO4").SetValue("U_ShippingClause", 0, "SHIPPER'S LOAD , COUNT & SEAL");
            Utils.SetBoxAndCargoQuantityDescription(SBOApp, BNOForm.UniqueID, new Arabic2Engish().NumberToString, "1");
            BNOForm.DataSources.DBDataSources.Item("@AVA_SE_OBNO").SetValue("U_ServiceType", 0, BNOForm.DataSources.DBDataSources.Item("@AVA_SE_BNO4").GetValue("U_BoxQty", 0));
        }
        #endregion
        private class Packing
        {
            public string BoxType { get; set; }
            public string BoxCode { get; set; }
            public string SealCode { get; set; }
        }
    }
}
